<template>
  <div class="detail-container">
    <Header />
    <div class="content">
      <button @click="goBack" class="back-btn">← 返回列表</button>
      
      <div class="member-detail-card">
        <h2>成员详情</h2>
        
        <!-- 新增头像展示区域 -->
        <div class="avatar-container">
          <img 
            :src="memberInfo.avatar || defaultAvatar" 
            alt="用户头像" 
            class="avatar-img"
          >
        </div>
        
        <div class="detail-section">
          <div class="detail-item">
            <span class="label">姓名：</span>
            <span class="value">{{ member.username }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">学院：</span>
            <span class="value">{{ memberInfo.college || '-' }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">部门：</span>
            <span class="value">{{ getDepartmentName(member.departmentId) }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">职位：</span>
            <span class="value">{{ member.position }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">联系方式：</span>
            <span class="value">{{ memberInfo.phone || '-' }}</span>
          </div>

          <div class="detail-item">
            <span class="label">入社时间：</span>
            <span class="value">{{ formatJoinTime(member.joinTime) }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">状态：</span>
            <span class="value">{{ member.status === 'active' ? '正常' : '退出' }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">荣誉：</span>
            <span class="value">{{ memberInfo.honor || '无' }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">备注：</span>
            <span class="value">{{ memberInfo.note || '无' }}</span>
          </div>
          
          <div class="detail-item">
            <span class="label">职责：</span>
            <span class="value">{{ memberInfo.duty || '无' }}</span>
          </div>
        </div>
        
        <div class="operation-buttons">
          <button @click="handleEdit" class="btn-edit">编辑</button>
          <button @click="handleChangeStatus" class="btn-status">
            {{ member.status === 'active' ? '设为退出' : '设为正常' }}
          </button>
          <button @click="handleDelete" class="btn-delete">删除</button>
        </div>
      </div>
      
      <div class="member-schedules">
        <h3>近期排班</h3>
        <table class="schedule-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>周次</th>
              <th>日期</th>
              <th>时间</th>
              <th>播稿主题</th>
              <th>搭档</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="schedule in memberSchedules" :key="schedule.scheduleId">
              <td>{{ schedule.scheduleId }}</td>  <!-- 正确字段：scheduleId -->
              <td>第{{ schedule.week }}周</td>
              <td>{{ formatScheduleDate(schedule.date) }}</td>  <!-- 格式化日期 -->
              <td>{{ formatScheduleTime(schedule.date) }}</td>  <!-- 从date中提取时间 -->
              <td>{{ schedule.topic }}</td>  <!-- 直接使用topic字段 -->
              <td>
                {{ getPartnerName(schedule.partner1Id) }}  <!-- 正确字段：partner1Id -->
                <span v-if="schedule.partner1Id && schedule.partner2Id">、</span>
                {{ getPartnerName(schedule.partner2Id) }}  <!-- 正确字段：partner2Id -->
              </td>
              <td>{{ schedule.status === 'scheduled' ? '已编排' : '已完成' }}</td>
            </tr>
            <tr v-if="memberSchedules.length === 0">
              <td colspan="7" class="no-data">暂无排班记录</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 编辑成员弹窗 - 增加荣誉编辑功能 -->
    <div v-if="showEditDialog" class="dialog-overlay">
      <div class="dialog">
        <div class="dialog-header">
          <h3>编辑成员</h3>
          <button @click="closeEditDialog" class="dialog-close">&times;</button>
        </div>
        <div class="dialog-content">
          <div class="form-group">
            <label>荣誉：</label>
            <textarea v-model="editForm.honor" rows="2" placeholder="请输入荣誉信息"></textarea>
          </div>
          <div class="form-group">
            <label>备注：</label>
            <textarea v-model="editForm.note" rows="3" placeholder="请输入备注信息"></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="saveEdit" class="btn-primary">保存</button>
          <button @click="closeEditDialog" class="btn-secondary">取消</button>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const memberId = parseInt(route.params.id)

// 成员数据
const member = ref({})
const memberInfo = ref({})
const memberSchedules = ref([])
const allThemes = ref([])
const allMembers = ref([])
// 默认头像地址
const defaultAvatar = 'https://picsum.photos/100/100?text=暂无头像'

// 编辑弹窗及表单数据
const showEditDialog = ref(false)
const editForm = reactive({
  honor: '',
  note: ''
})

// 部门映射表
const departmentMap = {
  1: '采播部',
  2: '电台部',
  3: '主持部',
  4: '新媒体部',
  5: '技术部',
  6: '办公室',
  7: '运营部',
  8: '摄影部',
  9: '网宣部'
}

// 获取部门名称
const getDepartmentName = (deptId) => {
  return departmentMap[deptId] || '未知部门'
}

// 格式化入社时间
const formatJoinTime = (time) => {
  if (!time) return '未填写'
  if (typeof time === 'string' && time.includes('-')) {
    return time.split('T')[0] // 处理日期字符串
  }
  return time
}

// 格式化日期（仅显示年月日）
const formatScheduleDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN'); // 输出：2025/1/12 或 2025-01-12（取决于浏览器）
};

// 格式化时间（仅显示时分）
const formatScheduleTime = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }); // 输出：16:00
};

// 获取主题名称
const getThemeName = (topicId) => {
  const theme = allThemes.value.find(t => t.topic_id === topicId)
  return theme ? theme.topic_name : '-'
}

// 获取搭档名称
const getPartnerName = (partnerId) => {
  if (!partnerId) return ''
  const partner = allMembers.value.find(m => m.id === partnerId)
  return partner ? partner.username : ''
}

// 获取成员详情
const fetchMemberDetail = async () => {
  try {
    // 获取用户基本信息
    const response = await fetch(`http://localhost:8080/user/${memberId}`)
    const result = await response.json()
    
    if (result.code === 200) {
      if (!result.data) {
        console.error('获取成员详情成功但未返回数据:', result)
        alert('获取成员信息失败：服务器未返回数据')
        router.push('/buzhang/caibo')
        return
      }

      member.value = result.data
      
      // 获取用户详细信息
      const infoResponse = await fetch(`http://localhost:8080/userInfo/user/${memberId}`)
      const infoResult = await infoResponse.json()
      
      if (infoResult.code === 200) {
        memberInfo.value = infoResult.data || {}
        // 初始化编辑表单数据
        editForm.honor = infoResult.data?.honor || ''
        editForm.note = infoResult.data?.note || ''
      } else {
        console.warn('获取用户详细信息失败:', infoResult.message)
        memberInfo.value = {}
      }
    } else {
      alert('获取成员信息失败: ' + (result.message || '未知错误'))
      router.push('/buzhang/caibo')
    }
  } catch (error) {
    console.error('获取成员详情失败:', error)
    alert('获取成员信息失败: ' + error.message)
    router.push('/buzhang/caibo')
  }
}

// 获取成员排班记录
const fetchMemberSchedules = async () => {
  try {
    const response = await fetch(`http://localhost:8080/schedule/user/${memberId}`)
    const result = await response.json()
    if (result.code === 200) {
      memberSchedules.value = result.data || []
    }
  } catch (error) {
    console.error('获取排班记录失败:', error)
  }
}

// 获取所有播稿主题
const fetchAllThemes = async () => {
  try {
    const response = await fetch('http://localhost:8080/topic_library/all')
    const result = await response.json()
    if (result.code === 200) {
      allThemes.value = result.data || []
    }
  } catch (error) {
    console.error('获取播稿主题失败:', error)
  }
}

// 获取所有成员
const fetchAllMembers = async () => {
  try {
    const response = await fetch('http://localhost:8080/user/all')
    const result = await response.json()
    if (result.code === 200) {
      allMembers.value = result.data || []
    }
  } catch (error) {
    console.error('获取所有成员失败:', error)
  }
}

// 返回列表页
const goBack = () => {
  router.push('/buzhang/caibo/memberManagement')
}

// 编辑成员 - 打开弹窗并初始化数据
const handleEdit = () => {
  showEditDialog.value = true
  editForm.honor = memberInfo.value.honor || ''
  editForm.note = memberInfo.value.note || ''
}

// 保存编辑
const saveEdit = async () => {
  try {
    if (!memberInfo.value.infoId) {
      // 如果没有用户信息，先创建
      const createResponse = await fetch('http://localhost:8080/userInfo/add', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          userId: memberId,
          note: editForm.note,
          college: memberInfo.value.college || '',
          phone: memberInfo.value.phone || '',
          honor: editForm.honor || ''
        })
      })
      
      const createResult = await createResponse.json()
      if (createResult.code === 200) {
        memberInfo.value = createResult.data
        showEditDialog.value = false
        fetchMemberDetail()
      } else {
        alert(createResult.message || '保存失败')
      }
    } else {
      // 更新现有用户信息
      const updateResponse = await fetch('http://localhost:8080/userInfo/update', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          infoId: memberInfo.value.infoId,
          note: editForm.note,
          college: memberInfo.value.college,
          phone: memberInfo.value.phone,
          honor: editForm.honor
        })
      })
      
      const updateResult = await updateResponse.json()
      if (updateResult.code === 200) {
        memberInfo.value.honor = editForm.honor
        memberInfo.value.note = editForm.note
        showEditDialog.value = false
      } else {
        alert(updateResult.message || '保存失败')
      }
    }
  } catch (error) {
    console.error('保存备注失败:', error)
    alert('保存失败，请重试')
  }
}

// 关闭编辑对话框
const closeEditDialog = () => {
  showEditDialog.value = false
}

// 更改成员状态
const handleChangeStatus = async () => {
  const newStatus = member.value.status === 'active' ? 'inactive' : 'active'
  const confirmMessage = newStatus === 'active' 
    ? '确定要重新启用该成员吗？' 
    : '确定要将该成员设为退出状态吗？'
  
  if (!confirm(confirmMessage)) return
  
  try {
    const response = await fetch(`http://localhost:8080/user/status/${memberId}/${newStatus}`, {
      method: 'PUT'
    })
    
    const result = await response.json()
    if (result.code === 200) {
      member.value.status = newStatus
      alert('状态更新成功')
    } else {
      alert(result.message || '操作失败')
    }
  } catch (error) {
    console.error('更改成员状态失败:', error)
    alert('操作失败，请重试')
  }
}

// 删除成员
const handleDelete = async () => {
  if (!memberInfo.value.note && !confirm('删除成员前需要在备注中说明退台原因。确定要删除该成员吗？')) return
  if (memberInfo.value.note && !confirm('确定要删除该成员吗？')) return
  
  try {
    // 先更新状态为inactive
    const statusResponse = await fetch(`http://localhost:8080/user/status/${memberId}/inactive`, {
      method: 'PUT'
    })
    
    const statusResult = await statusResponse.json()
    if (statusResult.code === 200) {
      member.value.status = 'inactive'
      alert('成员状态已更新为退出')
    } else {
      alert(statusResult.message || '操作失败')
    }
  } catch (error) {
    console.error('删除成员失败:', error)
    alert('操作失败，请重试')
  }
}

// 初始化数据
onMounted(() => {
  if (memberId) {
    fetchMemberDetail()
    fetchMemberSchedules()
    fetchAllThemes()
    fetchAllMembers()
  } else {
    alert('无效的成员ID')
    router.push('/buzhang/caibo')
  }
})
</script>

<style scoped>
.detail-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.content {
  flex: 1;
  max-width: 1000px;
  width: 100%;
  margin: 0 auto;
  padding: 20px;
}

.back-btn {
  background: none;
  border: none;
  color: #1890ff;
  cursor: pointer;
  font-size: 14px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.member-detail-card {
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

h2 {
  color: #1f2329;
  margin-top: 0;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  text-align: center;
}

h3 {
  color: #1f2329;
  margin-top: 0;
  margin-bottom: 20px;
}

/* 头像样式 */
.avatar-container {
  text-align: center;
  margin-bottom: 25px;
}

.avatar-img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #eee;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.detail-section {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 25px;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.label {
  width: 100px;
  font-weight: bold;
  color: #666;
}

.value {
  flex: 1;
  color: #333;
  word-break: break-word;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.btn-edit {
  background-color: #52c41a;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-edit:hover {
  background-color: #4aa918;
}

.btn-status {
  background-color: #faad14;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-status:hover {
  background-color: #d49600;
}

.btn-delete {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-delete:hover {
  background-color: #d9363e;
}

.member-schedules {
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.schedule-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.schedule-table th, .schedule-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.schedule-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 30px;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.dialog-content {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #666;
}

.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-primary {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #f0f0f0;
  color: #333;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
</style>
